package org.pjlib.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.MotionEvent;

import androidx.annotation.Nullable;

import org.pjlib.R;

/**
 * Created by ws on 2018/12/12.
 */
public class LImageView extends androidx.appcompat.widget.AppCompatImageView {
    private static final String TAG="LImageView";
    private int pressRes;
    private int noPressRes;
    private OnClickListener onClickListener;
    public LImageView(Context context) {
        this(context,null);
    }

    public LImageView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public LImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LImageView, defStyleAttr, 0);
        pressRes=a.getResourceId(R.styleable.LImageView_pressImgRes,0);
        noPressRes=a.getResourceId(R.styleable.LImageView_noPressImgRes,0);
        a.recycle();
        setImg(false);
    }

    public int getPressRes() {
        return pressRes;
    }

    public void setPressRes(int pressRes) {
        this.pressRes = pressRes;
    }

    public int getNoPressRes() {
        return noPressRes;
    }

    public void setNoPressRes(int noPressRes) {
        this.noPressRes = noPressRes;
    }

    private void setImg(boolean isPress){
        if(onClickListener==null){
            return;
        }
        if(pressRes==0 && noPressRes==0){
            if(isPress){
                this.animate().alpha(0.5f).start();
            }else {
                this.animate().alpha(1f).start();
            }
            return;
        }
        int res;
        if(isPress){
            res=pressRes==0?noPressRes:pressRes;
        }else {
            res=noPressRes==0?pressRes:noPressRes;
        }
        setImageResource(res);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                setImg(true);
                break;
            case MotionEvent.ACTION_UP:
                setImg(false);
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void setOnClickListener( @Nullable OnClickListener l) {
        super.setOnClickListener(l);
        onClickListener=l;
    }
}
